package com.siyougame.business.service.user;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.siyougame.business.controller.app.vo.ThirdUserDTO;
import com.siyougame.business.util.ThirdUserUtil;
import com.siyougame.common.exception.RRException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import com.siyougame.business.controller.admin.user.vo.*;
import com.siyougame.business.dal.dataobject.user.WxUserDO;
import com.siyougame.common.pojo.PageResult;

import com.siyougame.business.convert.user.WxUserConvert;
import com.siyougame.business.dal.mysql.user.WxUserMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import static com.siyougame.common.exception.util.ServiceExceptionUtil.exception;
import static com.siyougame.business.enums.ErrorCodeConstants.*;
import static com.siyougame.common.pojo.CommonResult.success;

/**
 * 微信用户 Service 实现类
 *
 * @author ${table.author}
 */
@Slf4j
@Service
public class WxUserServiceImpl extends ServiceImpl<WxUserMapper,  WxUserDO> implements WxUserService {

    @Resource
    private WxUserMapper wxUserMapper;
    @Resource
    private ThirdUserUtil thirdUserUtil;

    /**
     * 从三方查询用户信息到本地，并存储，暂定过期时间7天，但是用户应该不会一直使用7天
     * @param createReqVO 创建信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createWxUser(WxUserCreateReqVO createReqVO,String token) {

        ThirdUserDTO thirdUserDTO = thirdUserUtil.getUserDetail(createReqVO, token);
        if(thirdUserDTO.getCode() == null){
            throw new RRException("登录失败，请检查token是否正确");
        }
        String id = thirdUserDTO.getData().getId();
        String departmentId = thirdUserDTO.getData().getDepartmentId();
        log.info("请求token:{},三方登录返回数据：{}",token, JSONUtil.toJsonStr(thirdUserDTO));
        // if (!thirdUserDTO.getData().getId().equals("1104749388762185728")) {
        //
        //     log.error("三方返回错误，id不匹配{}", JSONUtil.toJsonStr(thirdUserDTO));
        // }

        //判断本地是否有这个用户，如果有就更新，如果没有就插入
        WxUserDO wxUser = wxUserMapper.selectOne(Wrappers.<WxUserDO>lambdaQuery()
                .eq(WxUserDO::getThirdUserId, id).eq(WxUserDO::getThirdDepartmentId, departmentId));
        if (wxUser == null) {
            wxUser = new WxUserDO();
            //wxUser.setId(id);
            wxUser.setThirdUserId(id);
            wxUser.setThirdDepartmentId(departmentId);
            wxUser.setNickname(thirdUserDTO.getData().getUsername());
            wxUser.setThirdDepartment(thirdUserDTO.getData().getDepartment());
            //当前时间+7天
            // 获取当前时间
            DateTime now = DateUtil.date();
            // 当前时间加 7 天 实际这里的过期时间暂无作用，因为我satoken 设置的过期时间是 7 天
            DateTime futureDate = DateUtil.offsetDay(now, 7);
            wxUser.setExpiresTime(futureDate);
            wxUser.setUserInfoJson(JSONUtil.toJsonStr(thirdUserDTO));
            wxUserMapper.insert(wxUser);
        }

        // 返回
        return wxUser.getId();
    }

    @Override
    public void updateWxUser(WxUserUpdateReqVO updateReqVO) {
        // 校验存在
        this.validateWxUserExists(updateReqVO.getId());
        // 更新
        WxUserDO updateObj = WxUserConvert.INSTANCE.convert(updateReqVO);
        wxUserMapper.updateById(updateObj);
    }

    @Override
    public void deleteWxUser(Long id) {
        // 校验存在
        this.validateWxUserExists(id);
        // 删除
        wxUserMapper.deleteById(id);
    }

    private void validateWxUserExists(Long id) {
        if (wxUserMapper.selectById(id) == null) {
            throw exception(WX_USER_NOT_EXISTS);
        }
    }

    @Override
    public WxUserDO getWxUser(Long id) {
        return wxUserMapper.selectById(id);
    }

    @Override
    public List<WxUserDO> getWxUserList(Collection<Long> ids) {
        return wxUserMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<WxUserDO> getWxUserPage(WxUserPageReqVO pageReqVO) {
        return wxUserMapper.selectPage(pageReqVO);
    }

    @Override
    public List<WxUserDO> getWxUserList(WxUserExportReqVO exportReqVO) {
        return wxUserMapper.selectList(exportReqVO);
    }

}
